package com.zyh.cxf;



import com.zyh.dao.KeyMapper;
import com.zyh.pojo.YyzlKey;
import com.zyh.service.FundPayResultService;
import com.zyh.util.safeutil.DESedeUtil;
import com.zyh.util.safeutil.SM2Utils;
import com.zyh.util.safeutil.Util;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.Map;


/**
 * @author shihan
 * @date 2020-12-04-13:55
 * 查询基金支付指令结果
 */
@Component
public class FundPayOrderResultImpl implements FundPayOrderResult {


    @Autowired
    private FundPayResultService fundPayResultService;

    @Autowired
    private KeyMapper keyMapper;







    @Override
    public String getFundPayResult(String xmlData) {
        Map<String, Object> keyMap = keyMapper.querykey();
        //查询加密的公钥
        String inencryptKey=(String)keyMap.get("PublicKey");
        String privateKey=(String)keyMap.get("PrivateKey");
        //第一步密钥解密
        System.err.println("密钥sm2私钥解密：");
        String plainText = null;
        try {
            plainText = new String(SM2Utils.decrypt(Util.hexToByte(privateKey), Util.hexToByte(inencryptKey)));
        } catch (IOException e) {
            e.printStackTrace();
        }
        System.out.println("密钥明文：" + plainText);

        // 第二步通过拿到的解密密钥进行报文解密
        String inresource = null;
        try {
            inresource = DESedeUtil.decrypt(xmlData, plainText);
        } catch (Exception e) {
            e.printStackTrace();
        }
        System.out.println("医保端明文："+ inresource);
        String retXml = fundPayResultService.queryResult(inresource);
        // 加密
        String outencryptStr =null;
        try {
             outencryptStr = DESedeUtil.encrypt(retXml, plainText);
        } catch (Exception e) {
            e.printStackTrace();
        }

        System.out.println("返回给医保的密文："+ outencryptStr);
       // 解密
        String outresource = null;
        try {
            outresource = DESedeUtil.decrypt(outencryptStr, plainText);
        } catch (Exception e) {
            e.printStackTrace();
        }
        System.out.println("返回给医保的明文："+ outresource);

        return outencryptStr;
    }




}
